import axios from 'axios'

const API_PREFIX = import.meta?.env?.VITE_API_PREFIX || ''

export async function fetchRecords({ page = 1, pageSize = 10 } = {}) {
  if (API_PREFIX) {
    const res = await axios.get(`${API_PREFIX}/records`, { params: { page, pageSize } })
    return res.data
  }
  const all = Array.from({ length: 30 }).map((_, i) => ({
    id: `r${i + 1}`,
    date: `2020-01-${String(30 - i).padStart(2, '0')} 15:20`,
    type: ['挂号', '问诊', '缴费', '检查'][i % 4],
    dept: '门诊外一科',
    doctor: '刘医生（主任医师）',
    hospital: '四川省保健院南苑'
  }))
  const start = (page - 1) * pageSize
  const items = all.slice(start, start + pageSize)
  return new Promise(resolve => setTimeout(() => resolve({ items, hasMore: start + pageSize < all.length }), 400))
}

const LOCAL_KEY = 'visitRecords'

export function addLocalRecord(record) {
  if (!record) return
  try {
    const list = JSON.parse(localStorage.getItem(LOCAL_KEY) || '[]')
    const merged = [record, ...list].slice(0, 100)
    localStorage.setItem(LOCAL_KEY, JSON.stringify(merged))
  } catch (_) {}
}

export function getLocalRecords() {
  try {
    return JSON.parse(localStorage.getItem(LOCAL_KEY) || '[]')
  } catch (_) { return [] }
}

export default { fetchRecords, addLocalRecord, getLocalRecords }


